package com.lmk.ms.autoconfigure.influx;

import com.influxdb.client.InfluxDBClient;
import com.influxdb.client.InfluxDBClientFactory;
import com.lmk.ms.common.db.influx.config.InfluxProperties;
import com.lmk.ms.common.db.influx.service.InfluxService;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * InfluxDB 自动配置类
 *
 * @author laomake@hotmail.com
 * @version 1.0
 * @date 2022/9/20
 */
@Configuration
@EnableConfigurationProperties(InfluxProperties.class)
@ConditionalOnProperty(value = "ms.config.db.influx.enabled", havingValue = "true", matchIfMissing = false)
public class InfluxAutoconfigure {

    InfluxProperties influxProperties;

    public InfluxAutoconfigure(InfluxProperties influxProperties) {
        this.influxProperties = influxProperties;
    }

    @Bean
    public InfluxDBClient influxDBClient() {
        InfluxDBClient influxDBClient = null;
        if (influxProperties.getVersion() == 1) {
            influxDBClient = InfluxDBClientFactory.createV1(
                    influxProperties.getUrl(),
                    influxProperties.getUsername(),
                    influxProperties.getPassword().toCharArray(),
                    influxProperties.getDatabase(),
                    influxProperties.getRetentionPolicy());
        } else {
            influxDBClient = InfluxDBClientFactory.create(
                    influxProperties.getUrl(),
                    influxProperties.getToken().toCharArray(),
                    influxProperties.getOrg(),
                    influxProperties.getBucket());
        }
        return influxDBClient;
    }

    @Bean
    public InfluxService influxService(InfluxDBClient influxDBClient) {
        return new InfluxService(influxProperties, influxDBClient);
    }
}

